package diko_parent.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import diko_parent.eduservice.entity.Subject;
import diko_parent.eduservice.entity.excel.subjectData;
import diko_parent.eduservice.entity.subject.OneSubject;
import diko_parent.eduservice.entity.subject.TwoSubject;
import diko_parent.eduservice.listener.SubjectExcelListener;
import diko_parent.eduservice.mapper.SubjectMapper;
import diko_parent.eduservice.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Emma-Li
 * @since 2020-09-23
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void saveSubject(MultipartFile file,SubjectService subjectService) {
        try{
            InputStream in = file.getInputStream();
            EasyExcel.read(in, subjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public List<OneSubject> getSubjectList() {
        //最终要的数据列表
        ArrayList<OneSubject> subjectList = new ArrayList<>();

        //获取一级分类数据记录
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",0);
        queryWrapper.orderByAsc("sort","id");
        List<Subject> subjects = baseMapper.selectList(queryWrapper);

        //获取二级分类数据记录
        QueryWrapper<Subject> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.ne("parent_id",0);
        queryWrapper1.orderByAsc("sort","id");
        List<Subject> subjects1 = baseMapper.selectList(queryWrapper1);

        //填充一级分类数据
        int count=subjects.size();
        for(int i=0;i<count;i++){
            Subject subject = subjects.get(i);

            //创建一级分类级别对象
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(subject,oneSubject);
            subjectList.add(oneSubject);

            //填充二级分类数据
            ArrayList<TwoSubject> twoSubjectList = new ArrayList<>();
            int count2=subjects1.size();
            for(int j=0;j<count2;j++){
                Subject subject1 = subjects1.get(j);
                if(subject.getId().equals(subject1.getParentId())){
                    //创建二级类别对象
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(subject1,twoSubject);
                    twoSubjectList.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjectList);
        }
        return subjectList;
    }
}
